<?php

include_once 'SPDO.class.php';
include_once 'piece.class.php';

class Utilisateur
{
	protected $ID;
	protected $droit;
	protected $login;
	protected $piece;
	protected $temperatureExt;

	public function __construct($m_login)
	{
		$this->login = $m_login;
		
		try 
		{
			$info = SPDO::pdo()->prepare("SELECT ID_Utilisateur, Droit FROM Utilisateur WHERE Login = :login");
			$info->execute(array('login' => $this->login));
			
			if($info->rowCount() == 0)
			{
				die("Erreur de transfert ServC a ServF");
			}
			else
			{
				while ($result = $info->fetch(PDO::FETCH_OBJ))
				{
					$this->ID = $result->ID_Utilisateur;
					$this->droit = $result->Droit;
				}
			}
			
			$temp = SPDO::pdo()->query("SELECT TemperatureExt FROM Temperature");
			
			while ($result = $temp->fetch(PDO::FETCH_OBJ))
			{
				$this->temperatureExt = $result->TemperatureExt;
			}
		}
		catch (PDOException $e)
		{
			die($e->getMessage());
		}
	}

	public function __get($nom)
	{
		if($nom == "piece")
		{
			$this->construitMaison();
			return $this->piece;
		}
	}
	
	public function construitMaison()
	{
		try
		{
			$recupPiece = SPDO::pdo()->prepare("SELECT * FROM Piece WHERE Droit >= :droit");
			$recupPiece->execute(array('droit' => $this->droit));
		
			$i = 0;
		
			while($result = $recupPiece->fetch(PDO::FETCH_OBJ))
			{
				$this->piece[$i] = new Piece($result->ID_Piece, $result->Nom_Piece, $result->Droit, $this->droit, $this->temperatureExt);
				$i++;
			}
		
			$recupPiece->closeCursor();
		}
		catch (PDOException $e)
		{
			die($e->getMessage());
		}
	}
	
	public function modifierPiece()
	{
		if(count($this->piece) != 0)
		{
			foreach ($this->piece AS $cle => $val)
			{
				$val->modifierPiece();
			}
		}
	}

	public function majPiece()
	{
		if(count($this->piece) != 0)
		{
			foreach ($this->piece AS $cle => $val)
			{
				$val->majEquipement();
			}
		}
	}
	
	public function ajouterEquipement()
	{
		if(count($this->piece) != 0)
		{
			foreach ($this->piece AS $cle => $val)
			{
				try 
				{
					$val->ajouterEquipement();
				}
				catch (DomotiqueException $e)
				{
					$e->notification();
				}				
			}
		}
	}
	
	public function ajouterPiece($nom)
	{
		try 
		{
			$insert = SPDO::pdo()->prepare("INSERT INTO Piece(Nom_Piece) VALUES (:nom)");
			$insert->execute(array('nom' => $nom));
			
			echo "<script type='text/javascript'>
								var notification = noty({type: 'success', layout: 'top', text: 'Piece créée'});
							</script>";
		}
		catch (PDOException $e)
		{
			die($e->getMessage());						
		}
	}
	
	public function supprimerEquipement()
	{
		if(count($this->piece) != 0)
		{
			foreach ($this->piece AS $cle => $val)
			{
				try
				{
					$val->supprimerEquipement();
				}
				catch (DomotiqueException $e)
				{
					$e->notification();
				}
			}
		}
	}
}
?>
